package com.love.zywanandroid.retrofit


import android.util.Log
import com.zat.mes.andrmes.event.TokenEventMessage
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.internal.http.HttpHeaders
import okio.Buffer
import org.greenrobot.eventbus.EventBus
import java.io.IOException
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit

/**
 * @author: zhangyu
 * @date: 2020-02-04 11:26
 * @description: 网络日志
 */
class LoggingInterceptor : Interceptor {
    private val UTF8 = Charset.forName("UTF-8")

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val requestBody = request.body()
        var body: String? = null
        if (requestBody != null) {
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            var charset: Charset? = UTF8
            val contentType = requestBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(UTF8)
            }
            body = buffer.readString(charset!!)
        }
        Log.d(
            "请求参数：", String.format(
                "发送请求\nmethod：%s\nurl：%s\nheaders:%s\nRequestBody:%s",
                request.method(), request.url(), request.headers(), body
            )
        )
        val startNs = System.nanoTime()
        val response = chain.proceed(request)
        val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)
        val headers = response.headers()
        val responseBody = response.body()
        var rBody: String? = null
        if (HttpHeaders.hasBody(response)) {
            val source = responseBody!!.source()
            // Buffer the entire body.
            source.request(java.lang.Long.MAX_VALUE)
            val buffer = source.buffer()
            var charset: Charset? = UTF8
            val contentType = responseBody.contentType()
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8)
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
            rBody = buffer.clone().readString(charset!!)
        }
        if ("failure".equals(headers.get("result"))) {
//            发送token 广播
            EventBus.getDefault().post(TokenEventMessage())
        }
        Log.d(
            "返回参数：", String.format(
                "响应url:%s\n收到响应:%s%s %s\nResponseBody:%s",
                request.url(), response.code(), response.message(), tookMs, rBody
            )
        )
        return response
    }

}

